//所有消息均需加上html标签
//			 加上时间戳
var send_btn = document.getElementById("send-msg-btn");
var msg_list = document.getElementById("msg-list");
var msg = document.getElementById("msg");
var date = new Date();
var user_name = document.getElementById("user-name");

var port = chrome.runtime.connect({name: "popup"});
port.postMessage({Msg: "open"});
port.onMessage.addListener(function(msg) {
    appendSpan("<p>"+msg.Msg.user+":"+msg.Msg.value+"</p>"+msg.Msg.htmlTime);
});


function appendSpan(text){
	var li=document.createElement("li");
	var span = msg_list.appendChild(li)
	span.innerHTML = text;
}

//获取时间,不包括日期
function getHtmlTime() {
	return "<span>"+date.toLocaleTimeString()+"<span>";
}

function getTime() {
	return date.getTime();
}

send_btn.onclick = function(){
	var Massage = {
		"value":msg.value,
		"id":getTime(),
		"htmlTime":getHtmlTime(),
		"user":user_name.value
	}
	//前端显示
	appendSpan("<p>"+user_name.value+":"+Massage.value+"</p>"+Massage.htmlTime);
	// 获取后台页面
	port.postMessage({Msg:"send",value:Massage});
	msg.value = "";	//clear
	desImg();
}
//修改昵称
user_name.addEventListener("change",function(){
	var name = user_name.value;
	setUserName(name);
})


function setUserName(name){
	chrome.storage.local.set({"name":name},function(){
		appendSpan("<h2>Wellcome:"+name+"<h2>");
		user_name.value = name;
	});
}
//获取昵称,如果没有则重新设置
function getUserName(){
	chrome.storage.local.get(function(obj){
		if(isNull(obj)){
			user_name.value = "Please Input your name!"
		}else{
			// appendSpan("<h2>Wellcome:"+name.name+"<h2>");
			user_name.value = obj.name;
		}
	});
}

function isNull(obj) {
	for(var name in obj){
		return false;
	}
	return true;
}

getUserName();


